package org.jeecg.modules.rest.handle;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.MD5Util;
import org.jeecg.config.thirdapp.ThirdAppTypeItemVo;
import org.springframework.web.client.HttpClientErrorException;

/**
 * 统一公共请求-SMS_WLWX
 */
public class CommonSmsWlwxRestHandle extends CommonRestHandle{

    /**
     * 获取token信息
     * @param config 第三方配置
     * @return ResultMsg
     */
    private ResultMsg getToken(ThirdAppTypeItemVo config){
        ResultMsg resultMsg = new ResultMsg();
        try {
            //发送token请求
            //QueryReq getTokenReq = new QueryReq();
            //getTokenReq.setCust_code(custCode);
            //String postData = JSON.toJSONString(getTokenReq);
            //String getTokenResp = HttpsClient.post(serviceBaseUrl + "/getToken", postData,
            //        "application/json", "utf-8");
            //JSONObject jsonObject = JSON.parseObject(getTokenResp);

            JSONObject paramObject = new JSONObject();
            paramObject.put("cust_code",config.getClientId());
            JSONObject jsonObject = super.postRest(config.getOauthHost()+":"+config.getHostPort() + "/getToken", paramObject);

            if (!"failed".equals(jsonObject.getString("status"))) {//判断是否获取token信息成功
                resultMsg.setSuccess(true);
                resultMsg.setData(jsonObject.toJSONString());
            } else {
                resultMsg.setSuccess(false);
                resultMsg.setCode(jsonObject.getString("respCode"));
                resultMsg.setMsg(jsonObject.getString("respMsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMsg.setSuccess(false);
            resultMsg.setCode("1000");
            resultMsg.setMsg("服务器出现未知异常");
        }
        return resultMsg;
    }
    /**
     * 统一封装公共类POST请求
     * @param apiPath
     * @param paramObject
     * @return
     * @throws JeecgBootException
     */
    public JSONObject postRest(ThirdAppTypeItemVo config, String apiPath, JSONObject paramObject) throws JeecgBootException {
        try {
            ResultMsg resultMsg = getToken(config);
            String sign = MD5Util.MD5Encode(paramObject.getString("content") + config.getClientSecret(),"utf-8");
            //req.setSign(sign);
            //req.setUid(uid);//业务ID
            //req.setCust_code(custCode);
            //req.setContent(content);
            //req.setDestMobiles(destMobiles); //接收号码，同时发送给多个号码时,号码之间用英文半角逗号分隔(,)
            //req.setNeed_report(needReport);//选填 状态报告需求与否，是 yes 否 no 默认yes
            //req.setSp_code(spCode);//选填 长号码
            //req.setMsgFmt(msgFmt);//选填 信息格式，0：ASCII串；3：短信写卡操作；4：二进制信息；8：UCS2编码；默认8
            //String postData = JSON.toJSONString(smsReq);
            //String sendSmsResp = HttpsClient.post(serviceBaseUrl + "/sendSms", postData, "application/json", "utf-8");
            //JSONObject jsonObject = JSON.parseObject(sendSmsResp);

            paramObject.put("cust_code",config.getClientId());
            paramObject.put("sign",sign);
            String url=config.getOauthHost()+":"+config.getHostPort()+apiPath;
            return super.postRest(url,paramObject);
        }catch (HttpClientErrorException e){
            // 403 Forbidden: [{"request_id":"a047f1f1e41a9c205ef63242f62d0666"
            // ,"error":"error_auth","message":"Invalid access_token."}]
            String errMsg=e.getMessage();
            if(errMsg.contains("[{") && errMsg.contains("}]")){
                String errJsonStr = errMsg.substring(errMsg.indexOf("[{")
                        ,errMsg.indexOf("}]",errMsg.indexOf("[{"))+2  );
                JSONArray jsonArray = JSONArray.parseArray(errJsonStr);
                JSONObject o = (JSONObject) jsonArray.get(0);
                return o;
            }
            JSONObject o = new JSONObject();
            o.put("error","error");
            o.put("message",e.getMessage());
            return o;
        }
    }
    /**
     * 统一封装公共类GET请求
     * @param apiPath
     * @param paramObject
     * @return
     * @throws Exception
     */
    public JSONObject getRest(ThirdAppTypeItemVo config,String apiPath,JSONObject paramObject) throws JeecgBootException {
        try {
            if(null == paramObject){
                paramObject=new JSONObject();
            }

            return super.getRest(config.getOauthHost(),paramObject);
        }catch (HttpClientErrorException e){
            String errMsg=e.getMessage();
            if(errMsg.contains("[{") && errMsg.contains("}]")){
                String errJsonStr = errMsg.substring(errMsg.indexOf("[{")
                        ,errMsg.indexOf("}]",errMsg.indexOf("[{"))+2  );
                JSONArray jsonArray = JSONArray.parseArray(errJsonStr);
                JSONObject o = (JSONObject) jsonArray.get(0);
                return o;
            }
            JSONObject o = new JSONObject();
            o.put("error","error");
            o.put("message",e.getMessage());
            return o;
        }
    }
}
